package com.token.wsset.soap;

import com.alibaba.fastjson.JSONObject;
import lombok.Setter;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * @author chenjianxiong 2020/6/23
 */
public abstract class SoapXML {
    private String soap = null;

    private final JSONObject inJson;
    @Setter
    private String username;

    @Setter
    private String password;



    public SoapXML(){
        inJson = new JSONObject();
    }


    /**
     * 组装SOAP XML字符
     * @return StringBuffer
     */
    public String getSoapXML(){
        if(soap == null){
            writeInJson(this.getClass(),this);
            StringBuffer str = new StringBuffer(1000);
            str.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:flow.webservice.token.com\">")
                    .append("<soapenv:Header/>")
                    .append("<soapenv:Body>")
                    .append("<urn:doFlowMain soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">")
                    .append(appendToParentNode())
                    .append("</urn:doFlowMain>")
                    .append("</soapenv:Body>")
                    .append("</soapenv:Envelope>");
            soap = str.toString();
        }
        return soap;
    }



    /**
     * 获取接口返回的节点名称
     * @return
     */

    private StringBuffer appendToParentNode(){
        StringBuffer soapcode = new StringBuffer(500);
        soapcode.append("<username xsi:type=\"xsd:string\">").append(username).append("</username>");
        soapcode.append("<password xsi:type=\"xsd:string\">").append(password).append("</password>");
        soapcode.append("<actiontype xsi:type=\"xsd:int\">").append(getActionType().getId()).append("</actiontype>");
        soapcode.append("<data xsi:type=\"xsd:string\">").append(inJson.toJSONString()).append("</data>");
        return soapcode;
    }

    private void writeInJson(Class<?> c,Object o){
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            String filedName = field.getName();
            try {
                String firstLetter = filedName.substring(0, 1).toUpperCase();
                String getter = "get" + firstLetter + filedName.substring(1);
                Method method = c.getMethod(getter);
                Object value = method.invoke(o);
                inJson.put(filedName,value);
            }catch (Exception e){
//                System.out.println("--->无函数：" + filedName);
            }
        }
    }

    protected abstract ActionTypeEnum getActionType();

    public String getReturnNodeName(){
        return "doFlowMainResponse";
    }
}

